/**
 * 2022年2月18日 13:33:55 chanchaw
 * 制造损失 - 品质异常
 * 1. 快速查找表格列定义：{field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
 * 2. 快速查找表格数据源搜索：let grid = $(`#${KENDO_GRID_ID}`).kendoGrid({
 */
const KENDO_GRID_ID = 'v_grid';
const EDIT_FORM_ID = 'form_setBadQty';// 双击表格行弹出的模态窗ID
const URL_SAVE = 'quality/save';
const URL_DATASOURCE_TABLE = 'quality/list';
// const BAD_CTL_ID = ['bad01','bad02','bad03','bad04','bad05','bad06','bad07','bad08',
//     'bad09','bad10','bad11','bad12','bad13','bad14','bad15',
//     'bad16','bad17','bad18','bad19'];
const BAD_CTL_ID = ['bad13','bad14','bad15',
    'bad16','bad17','bad18','bad19'];
const EDIT_DIALOG_WIDTH = 610;
const EDIT_DIALOG_HEIGHT = 530;
let MAINID;

;!(function ($)
{
    $.fn.setFormValue = function (options)
    {
        var $this = $(this);

        $.each(options, function (key, value)
        {
            var obj = $this.find("*[name=" + key + "]");

            if (obj.attr("type") == "checkbox")
            {
                if ($.type(value) === "boolean")
                {
                    obj.attr("checked", value);
                }

                if ($.type(value) === "object")
                {
                    $.each(value, function (i, item)
                    {
                        $this.find("*[name=" + key + "][value=" + i + "]").attr("checked", item);
                    })
                }
            }
            else if (obj.attr("type") == "radio")
            {
                $this.find("*[name=" + key + "][value=" + value + "]").attr("checked", true);
            }
            else
            {
                obj.val(value);
            }
        })
    }

})(jQuery)


$(function () {
    // 初始化页面
    // 1. 两个日期设置默认
    init();
    let buttonGroup = [
        {
            id: 'btn_cancel_add',
            size: 'small',
            text: '新增单据',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_cancel_add
        },
        {
            id: 'btn_cancel_fee',
            size: 'small',
            text: '添加费用',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_cancel_fee
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    grid_sum();
    grid_1();
    grid_2();
    bindEnterEvents();
    fee_grid();
    // getedatagrid();
})

function onTabSelect(title, index) {
    setTimeout(function () {
        switch (index) {
            case 0:
                $('#btn_cancel_add').linkbutton('enable');
                $('#btn_cancel_fee').linkbutton('enable');
                $('#btn_finishedOrAll').switchbutton('enable');
                $('#start').datebox('disable');
                $('#end').datebox('disable');
                break;
            case 1:
                $('#btn_cancel_add').linkbutton('enable');
                $('#btn_finishedOrAll').switchbutton('enable');
                $('#btn_finishedOrAll').switchbutton('enable');
                $('#start').datebox('disable');
                $('#end').datebox('disable');
                break;
            case 2:
                $('#btn_cancel_add').linkbutton('disable');
                $('#btn_cancel_fee').linkbutton('disable');
                $('#btn_finishedOrAll').switchbutton('disable');
                $('#start').datebox('enable');
                $('#end').datebox('enable');
                break;
        }
        btn_search();
    }, 0)
}

function grid_sum() {
    let SUFFIX = "";
    let mainId = new kendo.data.DataSource({data: []});
    let detailId = new kendo.data.DataSource({data: []});
    let billDate = new kendo.data.DataSource({data: []});
    let billCode = new kendo.data.DataSource({data: []});
    let ctName = new kendo.data.DataSource({data: []});
    let settlement = new kendo.data.DataSource({data: []});
    let contractNo = new kendo.data.DataSource({data: []});
    let orderNo = new kendo.data.DataSource({data: []});
    let deliveryDate = new kendo.data.DataSource({data: []});
    let invoice = new kendo.data.DataSource({data: []});
    let emName = new kendo.data.DataSource({data: []});
    let orderCategory = new kendo.data.DataSource({data: []});
    let orderTechnology = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});
    let productCategory = new kendo.data.DataSource({data: []});
    let productName = new kendo.data.DataSource({data: []});
    let productSpecification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let priceUnit = new kendo.data.DataSource({data: []});
    let qty = new kendo.data.DataSource({data: []});
    let price = new kendo.data.DataSource({data: []});
    let amount = new kendo.data.DataSource({data: []});
    let grayName = new kendo.data.DataSource({data: []});
    let graySpecification = new kendo.data.DataSource({data: []});
    let currencyType = new kendo.data.DataSource({data: []});
    let progress = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "orderMain/selectAllmain",
                dataType: "json",
                type: "GET",
                data: {
                    sdate: $('#start').datebox('getValue'),
                    edate: $('#end').datebox('getValue'),
                    flag: 2
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    qty: {type: "number"},
                    amount: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "qty", aggregate: "sum"},
            {field: "amount", aggregate: "sum"},

        ],
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            ctName.data(unique(data, 'ctName'));
            settlement.data(unique(data, 'settlement'));
            contractNo.data(unique(data, 'contractNo'));
            orderNo.data(unique(data, 'orderNo'));
            invoice.data(unique(data, 'invoice'));
            emName.data(unique(data, 'emName'));
            orderCategory.data(unique(data, 'orderCategory'));
            orderTechnology.data(unique(data, 'orderTechnology'));
            qty.data(unique(data, 'qty'));
            amount.data(unique(data, 'amount'));
            currencyType.data(unique(data, 'currencyType'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        // {
        //     field: "mainId",
        //     title: '主表主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        // {
        //     field: "detailId",
        //     title: '明细主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        {
            field: "billDate",
            title: '单据日期',
            width: 95,
            format: "{0: yyyy-MM-dd}",
            filterable: {multi: true, search: true, dataSource: billDate},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "ctName",
            title: '客户名称',
            width: 95,
            filterable: {multi: true, search: true, dataSource: ctName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "settlement",
            title: '结算户',
            width: 95,
            filterable: {multi: true, search: true, dataSource: settlement},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "contractNo",
            title: '合同号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: contractNo},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderNo",
            title: '订单号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderNo},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "invoice",
            title: '开票',
            width: 95,
            filterable: {multi: true, search: true, dataSource: invoice},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "emName",
            title: '业务员',
            width: 95,
            filterable: {multi: true, search: true, dataSource: emName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderCategory",
            title: '订单类别',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderCategory},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderTechnology",
            title: '订单工艺',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderTechnology},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "currencyType",
            title: '币种',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'qty',
            title: '订单数量',
            width: 70,
            template: item => {
                return item.qty ? parseFloat(item.qty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'amount',
            title: '金额(本币)',
            width: 70,
            template: item => {
                return item.amount ? parseFloat(item.amount).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n2}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "remark",
            title: '备注',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
    ];
    let grid = $(`#v_sum_grid`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "订单综合序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            changeBackgroundColor1();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_sum_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_sum_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        let id = dataItem.mainId;
        MAINID = id;
        $('#order_log').dialog('open');
        setStatus(dataItem.mainState);
        queryLog(id);
    });
}

function grid_1() {
    let SUFFIX = "";
    let mainId = new kendo.data.DataSource({data: []});
    let detailId = new kendo.data.DataSource({data: []});
    let billDate = new kendo.data.DataSource({data: []});
    let billCode = new kendo.data.DataSource({data: []});
    let ctName = new kendo.data.DataSource({data: []});
    let settlement = new kendo.data.DataSource({data: []});
    let contractNo = new kendo.data.DataSource({data: []});
    let orderNo = new kendo.data.DataSource({data: []});
    let deliveryDate = new kendo.data.DataSource({data: []});
    let invoice = new kendo.data.DataSource({data: []});
    let emName = new kendo.data.DataSource({data: []});
    let orderCategory = new kendo.data.DataSource({data: []});
    let orderTechnology = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});
    let productCategory = new kendo.data.DataSource({data: []});
    let productName = new kendo.data.DataSource({data: []});
    let productSpecification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let priceUnit = new kendo.data.DataSource({data: []});
    let qty = new kendo.data.DataSource({data: []});
    let price = new kendo.data.DataSource({data: []});
    let amount = new kendo.data.DataSource({data: []});
    let grayName = new kendo.data.DataSource({data: []});
    let graySpecification = new kendo.data.DataSource({data: []});
    let currencyType = new kendo.data.DataSource({data: []});
    let progress = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "orderMain/selectAllDTO",
                dataType: "json",
                type: "GET",
                data: {
                    sdate: $('#start').datebox('getValue'),
                    edate: $('#end').datebox('getValue'),
                    flag: 2
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    qty: {type: "number"},
                    amount1: {type: "number"},
                    amount2: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "qty", aggregate: "sum"},
            {field: "amount1", aggregate: "sum"},
            {field: "amount2", aggregate: "sum"},

        ],
        sort: {
            field: "bill_date",
            dir: "desc" // 使用"desc"进行倒序排列，如果是正序则使用"asc"
        },
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            mainId.data(unique(data, 'mainId'));
            detailId.data(unique(data, 'detailId'));
            billDate.data(unique(data, 'billDate'));
            billCode.data(unique(data, 'billCode'));
            ctName.data(unique(data, 'ctName'));
            settlement.data(unique(data, 'settlement'));
            contractNo.data(unique(data, 'contractNo'));
            orderNo.data(unique(data, 'orderNo'));
            deliveryDate.data(unique(data, 'deliveryDate'));
            invoice.data(unique(data, 'invoice'));
            emName.data(unique(data, 'emName'));
            orderCategory.data(unique(data, 'orderCategory'));
            orderTechnology.data(unique(data, 'orderTechnology'));
            remark.data(unique(data, 'remark'));
            productCategory.data(unique(data, 'productCategory'));
            productName.data(unique(data, 'productName'));
            productSpecification.data(unique(data, 'productSpecification'));
            color.data(unique(data, 'color'));
            priceUnit.data(unique(data, 'priceUnit'));
            qty.data(unique(data, 'qty'));
            price.data(unique(data, 'price'));
            amount.data(unique(data, 'amount'));
            grayName.data(unique(data, 'grayName'));
            graySpecification.data(unique(data, 'graySpecification'));
            currencyType.data(unique(data, 'currencyType'));
            progress.data(unique(data, 'progress'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        // {
        //     field: "mainId",
        //     title: '主表主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        // {
        //     field: "detailId",
        //     title: '明细主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        {
            field: "billDate",
            title: '单据日期',
            width: 95,
            format: "{0: yyyy-MM-dd}",
            filterable: {multi: true, search: true, dataSource: billDate},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "billCode",
            title: '单据编号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: billCode},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderNo",
            title: '订单号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderNo},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "ctName",
            title: '客户名称',
            width: 95,
            filterable: {multi: true, search: true, dataSource: ctName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "settlement",
            title: '结算户',
            width: 95,
            filterable: {multi: true, search: true, dataSource: settlement},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "contractNo",
            title: '合同号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: contractNo},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "currencyType",
            title: '币种',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "deliveryDate",
            title: '交期',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "invoice",
            title: '开票',
            width: 95,
            filterable: {multi: true, search: true, dataSource: invoice},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "emName",
            title: '业务员',
            width: 95,
            filterable: {multi: true, search: true, dataSource: emName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderCategory",
            title: '订单类别',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderCategory},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "orderTechnology",
            title: '订单工艺',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderTechnology},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: "productCategory",
        //     title: '成品品种',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: productCategory},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: "productName",
            title: '成品品名',
            width: 95,
            filterable: {multi: true, search: true, dataSource: productName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "productSpecification",
            title: '成品规格',
            width: 95,
            filterable: {multi: true, search: true, dataSource: productSpecification},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "color",
            title: '颜色',
            width: 95,
            filterable: {multi: true, search: true, dataSource: color},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "priceUnit",
            title: '计价单位',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'qty',
            title: '数量',
            width: 70,
            template: item => {
                return item.qty ? parseFloat(item.qty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'price',
            title: '单价',
            width: 70,
            template: item => {
                return item.price ? parseFloat(item.price).toFixed(2) : '';
            },
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'amount1',
            title: '金额(本币)',
            width: 70,
            template: item => {
                return item.amount1 ? parseFloat(item.amount1).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n2}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'amount2',
            title: '金额(外币)',
            width: 70,
            template: item => {
                return item.amount2 ? parseFloat(item.amount2).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n2}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: "grayName",
        //     title: '白坯品名',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: grayName},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "graySpecification",
        //     title: '白坯规格',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: graySpecification},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: "progress",
            title: '生产进度',
            width: 95,
            filterable: {multi: true, search: true, dataSource: progress},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "remark",
            title: '备注',
            width: 150,
            filterable: {multi: true, search: true, dataSource: remark},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
    ];
    let grid = $(`#${KENDO_GRID_ID}`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "订单明细序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            changeBackgroundColor();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        let id = dataItem.mainId;
        MAINID = id;
        $('#order_log').dialog('open');
        setStatus(dataItem.mainState);
        queryLog(id);
    });
}

function grid_2() {
    let SUFFIX = "";
    let mainId = new kendo.data.DataSource({data: []});
    let detailId = new kendo.data.DataSource({data: []});
    let billDate = new kendo.data.DataSource({data: []});
    let billCode = new kendo.data.DataSource({data: []});
    let ctName = new kendo.data.DataSource({data: []});
    let settlement = new kendo.data.DataSource({data: []});
    let contractNo = new kendo.data.DataSource({data: []});
    let orderNo = new kendo.data.DataSource({data: []});
    let deliveryDate = new kendo.data.DataSource({data: []});
    let invoice = new kendo.data.DataSource({data: []});
    let emName = new kendo.data.DataSource({data: []});
    let orderCategory = new kendo.data.DataSource({data: []});
    let orderTechnology = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});
    let productCategory = new kendo.data.DataSource({data: []});
    let productName = new kendo.data.DataSource({data: []});
    let productSpecification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let priceUnit = new kendo.data.DataSource({data: []});
    let qty = new kendo.data.DataSource({data: []});
    let price = new kendo.data.DataSource({data: []});
    let amount = new kendo.data.DataSource({data: []});
    let grayName = new kendo.data.DataSource({data: []});
    let graySpecification = new kendo.data.DataSource({data: []});
    let currencyType = new kendo.data.DataSource({data: []});
    let itemName = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "orderFee/selectAllByDate",
                dataType: "json",
                type: "GET",
                data: {
                    sdate: $('#start').datebox('getValue'),
                    edate: $('#end').datebox('getValue')
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    // qty: {type: "number"},
                    amount: {type: "number"},
                    // amount2: {type: "number"},
                }
            }
        },
        aggregate: [
            // {field: "qty", aggregate: "sum"},
            {field: "amount", aggregate: "sum"},
            // {field: "amount2", aggregate: "sum"},

        ],
        sort: {
            field: "bill_date",
            dir: "desc" // 使用"desc"进行倒序排列，如果是正序则使用"asc"
        },
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            mainId.data(unique(data, 'mainId'));
            detailId.data(unique(data, 'detailId'));
            billDate.data(unique(data, 'billDate'));
            billCode.data(unique(data, 'billCode'));
            ctName.data(unique(data, 'ctName'));
            settlement.data(unique(data, 'settlement'));
            contractNo.data(unique(data, 'contractNo'));
            orderNo.data(unique(data, 'orderNo'));
            deliveryDate.data(unique(data, 'deliveryDate'));
            invoice.data(unique(data, 'invoice'));
            emName.data(unique(data, 'emName'));
            orderCategory.data(unique(data, 'orderCategory'));
            orderTechnology.data(unique(data, 'orderTechnology'));
            remark.data(unique(data, 'remark'));
            productCategory.data(unique(data, 'productCategory'));
            productName.data(unique(data, 'productName'));
            productSpecification.data(unique(data, 'productSpecification'));
            color.data(unique(data, 'color'));
            priceUnit.data(unique(data, 'priceUnit'));
            qty.data(unique(data, 'qty'));
            price.data(unique(data, 'price'));
            amount.data(unique(data, 'amount'));
            grayName.data(unique(data, 'grayName'));
            graySpecification.data(unique(data, 'graySpecification'));
            currencyType.data(unique(data, 'currencyType'));
            itemName.data(unique(data, 'itemName'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        // {
        //     field: "mainId",
        //     title: '主表主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        // {
        //     field: "detailId",
        //     title: '明细主键',
        //     hidden: true,
        //     width: 93,
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;white-space: normal;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        // },
        {
            field: "billDate",
            title: '单据日期',
            width: 95,
            format: "{0: yyyy-MM-dd}",
            filterable: {multi: true, search: true, dataSource: billDate},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: "billCode",
        //     title: '单据编号',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: billCode},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: "orderNo",
            title: '订单号',
            width: 95,
            filterable: {multi: true, search: true, dataSource: orderNo},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "ctName",
            title: '客户名称',
            width: 95,
            filterable: {multi: true, search: true, dataSource: ctName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: "settlement",
        //     title: '结算户',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: settlement},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "contractNo",
        //     title: '合同号',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: contractNo},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "currencyType",
        //     title: '币种',
        //     width: 95,
        //     filterable: {multi: true, search: true},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "deliveryDate",
        //     title: '交期',
        //     width: 95,
        //     filterable: {multi: true, search: true},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "invoice",
        //     title: '开票',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: invoice},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "emName",
        //     title: '业务员',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: emName},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "orderCategory",
        //     title: '订单类别',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: orderCategory},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "orderTechnology",
        //     title: '订单工艺',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: orderTechnology},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        // {
        //     field: "productCategory",
        //     title: '成品品种',
        //     width: 95,
        //     filterable: {multi: true, search: true, dataSource: productCategory},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: "itemName",
            title: '费用类型',
            width: 95,
            filterable: {multi: true, search: true, dataSource: itemName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'amount',
            title: '金额(本币)',
            width: 70,
            template: item => {
                return item.amount ? parseFloat(item.amount).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n2}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        // {
        //     field: 'amount2',
        //     title: '金额(外币)',
        //     width: 70,
        //     template: item => {
        //         return item.amount2 ? parseFloat(item.amount2).toFixed(2) : '';
        //     },
        //     footerTemplate: '#=kendo.format("{0:n2}",sum)#',
        //     footerAttributes: {style: 'text-align:right;'},
        //     format: "{0:n2}",
        //     filterable: false,
        //     attributes: {'class': 'kendo-custum-number'},
        //     headerAttributes: {style: 'text-align:center;'}
        // },
        {
            field: "remark",
            title: '备注',
            width: 150,
            filterable: {multi: true, search: true, dataSource: remark},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "memo01",
            title: ' ',
            width: 500,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
    ];
    let grid = $(`#v_fee_grid`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "订单费用序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            // changeBackgroundColor();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_fee_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_fee_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        let id = dataItem.mainId;
        FEEPID = id;
        orderFee = {billDate: dataItem.billDate, client: dataItem.ctName, orderNo: dataItem.orderNo};
        $('#fee_log').dialog('open');
        $("#fee_form").form('load', orderFee);
        $("#order_fee_grid").datagrid('load', {id: FEEPID});
    });
}

let stateFlag = 2;

//开关
function finishedOrAll() {
    let value = $('#btn_finishedOrAll').switchbutton('options').checked;
    if (value) {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
        stateFlag = 1;
        btn_search();
    } else {
        $('#start').datebox('disable');
        $('#end').datebox('disable');
        stateFlag = 2;
        btn_search();
    }
}

//查询单据
function queryLog(id) {
    $.ajax({
        url: 'orderMain/selectDTO/' + id,
        contentType: 'application/json',
        type: 'post',
        dataType: 'json',
        success: function (data) {
            let mainDTO = data.data;
            if (mainDTO) {
                $('#billCode').textbox('setValue',mainDTO.billCode);
                $('#billDate').datebox('setValue',mainDTO.billDate);
                $('#clientId').combobox('setValue',mainDTO.clientId);
                $('#settlement').textbox('setValue',mainDTO.settlement);
                $('#contractNo').textbox('setValue',mainDTO.contractNo);
                $('#orderNo').textbox('setValue',mainDTO.orderNo);
                $('#deliveryDate').datebox('setValue',mainDTO.deliveryDate);
                $('#invoice').combobox('setValue',mainDTO.invoice);
                $('#empId').combobox('setValue',mainDTO.empId);
                $('#orderCategory').combobox('setValue',mainDTO.orderCategory);
                $('#currencyType').combobox('setValue',mainDTO.currencyType);
                $('#orderTechnology').textbox('setValue',mainDTO.orderTechnology);
                $('#remark').textbox('setValue',mainDTO.remark);
                $('#order_detail_grid').edatagrid('loadData', mainDTO.detailList);
            } else {
                $.messager.alert('警告', '未查询到数据!', 'warning');
                $('#order_detail_grid').datagrid('reload');
                $('#order_log').dialog('close');
                MAINID = null;
            }
        }
    })
}

/*============================================= 单据模态窗 ================================================*/

$("#order_detail_grid").edatagrid({
    data: [],
    striped: true,
    fit: true,
    // autoSave: true,
    sortable: true,
    rownumbers: true,
    remoteSort: false,
    singleSelect: true,
    showFooter: true,
    height: 'auto',
    columns: [[
        {title: '编号', field: 'id', hidden: true, width: 50, align: 'center', halign: 'center'},
        {
            title: '成品品名',
            field: 'productName',
            width: 150,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {required: false}}
        },
        // {
        //     title: '成品品种',
        //     field: 'productCategory',
        //     width: 100,
        //     align: 'center',
        //     halign: 'center',
        //     editor: {type: 'textbox', options: {}}
        // },
        {
            title: '成品规格',
            field: 'productSpecification',
            width: 120,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {}}
        },
        {
            title: '颜色',
            field: 'color',
            width: 170,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {}}
        },
        {
            title: '计价单位',
            field: 'priceUnit',
            width: 100,
            align: 'center',
            halign: 'center',
            editor: {
                type: 'combobox', options: {
                    url:'jcSimple/listQuery',
                    method: 'GET',
                    textField: 'sid',
                    valueField: 'sid',
                    panelHeight: 230,
                    onShowPanel:function(){
                        $(this).combobox('reload','jcSimple/listQuery');
                    },
                    onLoadSuccess: function() {
                    },
                    loadFilter: function (data) {
                        let item = [];
                        for (let i = 0; i < data.length; i++) {
                            if (data[i].category == '计价单位') item.push(data[i]);
                        }
                        return item;
                    }
                }
            }
        },
        {
            title: '数量',
            field: 'qty',
            width: 100,
            align: 'right',
            halign: 'center',
            formatter: formatter,
            editor: {type: "numberbox", options: {readonly: false, required: true, precision: 2}}
        },
        {
            title: '单价',
            field: 'price',
            width: 100,
            align: 'right',
            halign: 'center',
            formatter: formatter2,
            editor: {type: "numberbox", options: {readonly: false, precision: 2, required: true}}
        },
        {
            title: '金额',
            field: 'amount',
            width: 100,
            align: 'right',
            halign: 'center',
            formatter: formatter2,
            editor: {type: "numberbox", options: {readonly: true, precision: 2}}
        },
        /*{
            title: '白坯品名',
            field: 'grayName',
            width: 150,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {}}
        },
        {
            title: '白坯规格',
            field: 'graySpecification',
            width: 150,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {}}
        },*/
        {
            title: '备注',
            field: 'remark',
            width: 200,
            align: 'center',
            halign: 'center',
            editor: {type: 'textbox', options: {}}
        },
    ]],
    onLoadSuccess: function (data) {
        compute();
        $(this).datagrid('resize');
    },
    onSave: function (index, row) {
        compute();
    },
    onDestroy: function (index, row) {
        compute();
    },
    onEdit: function (i, r) {
        onSelect_money(i);
    },
    onSelect: function (i, d) {
    },
    onAdd: function (i, r) {
        r.pairNO = null;
        r.id = null;
        onSelect_money(i);
    },
    onResizeColumn: function (f, w) {
        if (w < 30) {
            if (f == 'clientId' || f == 'kilo' || f == 'billtypeId' || f == 'cutterId') {
                $.messager.show({title: '提示', msg: '无法隐藏该列,因为该列为必输项'});
                return;
            }
            $(this).datagrid('hideColumn', f);
            $.post("deploy/update.do", {menuId: 301, hidden: true, width: w, fieldname: f}, function (data) {
                if (data.state == 200) {
                    sessionStorage.removeItem('bp_bpbill');
                }
            }, "json");
        } else {
            $.post("deploy/update.do", {menuId: 301, hidden: false, width: w, fieldname: f}, function (data) {
                if (data.state == 200) {
                    sessionStorage.removeItem('bp_bpbill');
                }
            }, "json");
        }
    },
});

function formatter(value, row, index) {
    return value ? parseFloat(value).toFixed(1) : null;
}

function formatter2(value, row, index) {
    return value ? parseFloat(value).toFixed(2) : null;
}

function compute() {
    let data = $('#order_detail_grid').edatagrid('getRows');
    let qte = 0, amount = 0;
    for (let i = data.length - 1; i >= 0; i--) {
        qte += data[i].qty ? parseFloat(data[i].qty) : 0;
        amount += data[i].amount ? parseFloat(data[i].amount) : 0;
    }
    $('#order_detail_grid').edatagrid('reloadFooter', [{
        name: '合计',
        qty: qte.toFixed(2),
        amount: amount.toFixed(2),
    }]);
}

//网格金额自动计算事件
function onSelect_money(rowIndex) {
    var rowData = $('#order_detail_grid').datagrid('getRows')[rowIndex];  // rowIndex 为行号
    let qty = $('#order_detail_grid').edatagrid('getEditor', {field: 'qty', index: rowIndex});
    let price = $('#order_detail_grid').edatagrid('getEditor', {field: 'price', index: rowIndex});
    let amount = $('#order_detail_grid').edatagrid('getEditor', {field: 'amount', index: rowIndex});
    let productName = $('#order_detail_grid').edatagrid('getEditor', {field: 'productName', index: rowIndex});
    let grayName = $('#order_detail_grid').edatagrid('getEditor', {field: 'grayName', index: rowIndex});
    let productSpecification = $('#order_detail_grid').edatagrid('getEditor', {field: 'productSpecification', index: rowIndex});
    let graySpecification = $('#order_detail_grid').edatagrid('getEditor', {field: 'graySpecification', index: rowIndex});
    let priceUnit = $('#order_detail_grid').edatagrid('getEditor', {field: 'priceUnit', index: rowIndex});
    price.target.numberbox({
        onChange: function (n, o) {
            let q = $(qty.target).numberbox('getValue') || 0;
            amount.target.numberbox('setValue', n * q);
        }
    });
    qty.target.numberbox({
        onChange: function (n, o) {
            let p = $(price.target).numberbox('getValue') || 0;
            amount.target.numberbox('setValue', n * p);
        }
    });
    productName.target.textbox({
        onChange: function (n, o) {
            let p = $(productName.target).textbox('getValue') || '';
            grayName.target.textbox('setValue', p);
        }
    });
    productSpecification.target.textbox({
        onChange: function (n, o) {
            let p = $(productSpecification.target).textbox('getValue') || '';
            graySpecification.target.textbox('setValue', p);
        }
    });
    $(priceUnit.target).combobox('setValue', rowData.priceUnit?rowData.priceUnit:'公斤');
}

function category_loadFilter(data) {
    let item = [];
    for (let i = 0; i < data.length; i++) {
        if (data[i].category == '订单类别') item.push(data[i]);
    }
    return item;
}

// 保存
function btn_saveData() {
    // 1. 获取当前编辑的行索引
    var editIndex = $('#order_detail_grid').datagrid('getRowIndex', $('#order_detail_grid').datagrid('getSelected'));
    // 2. 如果存在编辑中的行，先结束编辑
    if (editIndex >= 0) {
        $('#order_detail_grid').datagrid('endEdit', editIndex);
    }
    let url;
    if (MAINID) url = 'orderMain/updateDTO';
    else url = 'orderMain/insertDTO';
    let rows = $('#order_detail_grid').edatagrid('getRows');
    let detail = [];
    for (let i = 0; i < rows.length; i++) {
        if (rows[i].productName &&
            rows[i].qty &&
            rows[i].price &&
            rows[i].amount) detail.push(rows[i]);
    }
    if (detail.length > 0){
        let record = {
            id: MAINID,
            state: STATUS == 0 ? 1 : STATUS,
            billDate: $('#billDate').datebox('getValue'),
            clientId: $('#clientId').combobox('getValue'),
            settlement: $('#settlement').textbox('getValue'),
            contractNo: $('#contractNo').textbox('getValue'),
            orderNo: $('#orderNo').textbox('getValue'),
            deliveryDate: $('#deliveryDate').datebox('getValue'),
            invoice: $('#invoice').combobox('getValue'),
            empId: $('#empId').combobox('getValue'),
            orderCategory: $('#orderCategory').combobox('getValue'),
            currencyType: $('#currencyType').combobox('getValue'),
            orderTechnology: $('#orderTechnology').textbox('getValue'),
            remark: $('#remark').textbox('getValue')
        }
        if (!record.clientId) {
            $.messager.alert('警告', '客户不允许为空!', 'warning');
            return;
        }
        if (!record.orderCategory) {
            $.messager.alert('警告', '订单类别不允许为空!', 'warning');
            return;
        }
        if (!record.currencyType) {
            $.messager.alert('警告', '币种不允许为空!', 'warning');
            return;
        }
        if (!record.orderTechnology) {
            $.messager.alert('警告', '订单工艺不允许为空!', 'warning');
            return;
        }
        if (!record.orderNo) {
            $.messager.alert('警告', '订单号不允许为空!', 'warning');
            return;
        }
        if (record.deliveryDate && record.billDate > record.deliveryDate) {
            $.messager.alert('警告', '交期不允许早于订单日期!', 'warning');
            return;
        }
        record.detailList = detail;
        $.ajax({
            url: url,
            contentType: 'application/json',
            data: JSON.stringify(record),
            type: 'post',
            dataType: 'json',
            success: function (data) {
                console.log(data);
                if (data.id){
                    btn_search();
                    if (STATUS == 0){
                        STATUS = 1;
                    } else {
                        STATUS = data.state;
                    }
                    MAINID = data.id;
                    setStatus(STATUS);
                    queryLog(MAINID);
                    $.messager.show({title: '提示', msg: '成功'});
                } else {
                    $.messager.show({title: '提示', msg: data.message});
                }
            }
        })
        // $('#order_log').dialog('close');
    } else {
        $.messager.alert('警告', '未录入明细!', 'warning');
    }
}

let STATUS = 0;

function setStatus(s) {
    STATUS = s;
    switch (s) {
        case 0://修改状态
            enableFormAllControl($("#form"));
            $('#img_state').addClass('hidden');
            $('#img_state_01').addClass('hidden');
            $('#order_detail_grid').edatagrid('enableEditing');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addBill" ||
                    $(this).attr("id") == "btn_billOk" ||
                    $(this).attr("id") == "btn_deleteBill" ||
                    $(this).attr("id") == "btn_billNo" ||
                    $(this).attr("id") == "btn_copyBill" ||
                    $(this).attr("id") == 'btn_updateData') {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        case 1://已保存状态
            disableFormAllControl($("#form"));
            $('#img_state').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state_01').addClass('hidden');
            $('#img_state').addClass('img-save');
            $('#order_detail_grid').edatagrid('disableEditing');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addRow" ||
                    $(this).attr("id") == "btn_saveData" ||
                    $(this).attr("id") == "btn_copyRow" ||
                    $(this).attr("id") == "showTechModal" ||
                    $(this).attr("id") == "btn_delectRow" ||
                    $(this).attr("id") == "btn_billNo") {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        case 2://已完成状态
            disableFormAllControl($("#form"));
            $('#img_state').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state_01').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state').addClass('img-save');
            $('#img_state_01').addClass('img_finished');
            $('#order_detail_grid').edatagrid('disableEditing');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addBill" ||
                    $(this).attr("id") == "btn_addRow" ||
                    $(this).attr("id") == "btn_updateData" ||
                    $(this).attr("id") == "btn_copyBill" ||
                    $(this).attr("id") == "btn_deleteBill" ||
                    $(this).attr("id") == "btn_saveData" ||
                    $(this).attr("id") == "btn_copyRow" ||
                    $(this).attr("id") == "btn_delectRow" ||
                    $(this).attr("id") == "btn_billOk" ||
                    $(this).attr("id") == 'btn_copyBill') {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        // case '3':
        //     $('#img_state').removeClass('img-delete img-audit img-save hidden');
        //     $('#img_state').addClass('img-cancel');
        //     $('#e_grid').edatagrid('disableEditing');
        //     disableFormEdit($('#form'))
        //     $('#btn_group .easyui-linkbutton').each(function () {
        //         let title = $(this).linkbutton('options').text;
        //         if (['新增单据', '上张', '下张', '关闭'].indexOf(title) >= 0) {
        //             $(this).linkbutton('enable');
        //         } else {
        //             $(this).linkbutton('disable');
        //         }
        //     })
        //     break;
    }
}

//新增单据
function btn_addBill() {
    setStatus(0);
    clear_log();
}

//模态窗-删除单据
function btn_deleteBill() {
    $.messager.confirm('确认', '确定删除本单据吗？不可恢复！', function (r) {
        if (r) {
            var ids = [];
            ids.push(MAINID);
            $.ajax({
                url: 'orderMain/deleteByIds',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                    if (data.success) {
                        btn_close_log();
                        btn_search();
                        $.messager.show({title: '提示', msg: '成功'});
                    } else {
                        $.messager.show({title: '提示', msg: data.message});
                    }
                }
            })
        }
    })
}

function btn_updateData(){
    setStatus(0)
}

//复制单据
function btn_copyBill() {
    MAINID = null;
    setStatus(0);
    $('#billCode').textbox('clear');
    $('#orderNo').textbox('clear');
    $('#contractNo').textbox('clear');
    var rows = $('#order_detail_grid').datagrid('getRows');  // 获取所有行数据
    // 遍历每行并删除id字段
    for (var i = 0; i < rows.length; i++) {
        delete rows[i].id;
    }
    // 刷新表格（可选，仅UI更新需要）
    $('#order_detail_grid').datagrid('loadData', rows);
}

//新增行
function btn_addRow() {
    $('#order_detail_grid').edatagrid('appendRow', {});
}

//复制行
function btn_copyRow() {
    $('#order_detail_grid').edatagrid('saveRow');
    var row = $('#order_detail_grid').datagrid('getSelected');  // 获取选中行
    if (!row) {
        $.messager.alert('提示', '请先选中一行！', 'info');
        return;
    }
    // 获取选中行的索引
    var index = $('#order_detail_grid').datagrid('getRowIndex', row);
    // 复制行数据（深拷贝避免引用问题）
    var newRow = $.extend({}, row);
    delete newRow.id;  // 移除ID（假设ID是自增主键）
    // 在选中行下方插入新行（而不是追加到最后）
    $('#order_detail_grid').datagrid('insertRow', {
        index: index + 1,  // 在选中行的下一行插入
        row: newRow
    });
    // 选中新插入的行
    $('#order_detail_grid').datagrid('selectRow', index + 1);
}

//删除行
function btn_delectRow () {
    var row = $('#order_detail_grid').edatagrid('getSelected');//获取选中行
    if (row){
        var index = $('#order_detail_grid').edatagrid('getRowIndex', row);//选中行索引
        $.messager.confirm('确认', '确定删除前选中行吗？不可恢复！', function (r) {
            if (r) {
                $('#order_detail_grid').edatagrid('deleteRow', index);
            }
        })
    } else {
        $.messager.alert('警告', '请先选中行!', 'warning');
    }
}

//订单完成
function btn_billOk() {
    setStatus(2);
    btn_saveData();
}

//订单取消完成
function btn_billNo() {
    setStatus(1);
    btn_saveData();
}

//关闭模态窗
function btn_close_log() {
    if (STATUS == 0) {
        $.messager.confirm('确认', '操作未保存，确定继续退出吗？', function (r) {
            if (r) {
                clear_log();
                $('#order_log').dialog('close');
            }
        })
    }else {
        clear_log();
        $('#order_log').dialog('close');
    }
}

//清空模态窗所有内容
function clear_log() {
    $('#billDate').datebox('setValue', getCurrentDate());
    $('#billCode').textbox('clear');
    $('#clientId').combobox('clear');
    $('#settlement').textbox('clear');
    $('#contractNo').textbox('clear');
    $('#orderNo').textbox('clear');
    $('#deliveryDate').datebox('clear');
    $('#invoice').combobox('clear');
    $('#empId').combobox('clear');
    $('#orderCategory').combobox('setValue', '出口订单');
    $('#currencyType').combobox('setValue', 'RMB');
    $('#orderTechnology').textbox('clear');
    $('#remark').textbox('clear');
    $('#order_detail_grid').datagrid('reload');
    $('#order_detail_grid').datagrid('loadData', { total: 0, rows: [] });
    MAINID = null;
    //  填充空行
    for (let i = 0; i < 5; i++) {
        $('#order_detail_grid').edatagrid('appendRow', {});
    }
}

//订单工艺选择模态窗
function showTechModal() {
    $('#techModal').dialog('open');
}

function loadTechOptions() {
    // 清空原有内容
    $('#techOptionsContainer').empty().html('加载中...');

    // 发送AJAX请求获取数据（示例使用jQuery）
    $.ajax({
        url: 'jcSimple/listQuery',  // 替换为你的真实接口地址
        method: 'GET',
        success: function(response) {
            // 清空容器
            $('#techOptionsContainer').empty();

            let item = []
            for (let i = 0; i < response.length; i++) {
                if (response[i].category == '订单工艺') item.push({value: response[i].sid, name: response[i].sid});
            }
            // 遍历数据创建选项
            item.forEach(function(tech) {
                const label = $('<label>').addClass('option-item');
                const input = $('<input>', {
                    type: 'checkbox',
                    name: 'techOption',
                    value: tech.value,
                    style: 'transform:scale(1.3); margin-right:8px;'
                });

                // 组合元素
                label.append(input).append(document.createTextNode(' ' + tech.name));
                $('#techOptionsContainer').append(label).append('<br>');
            });
        },
        error: function() {
            // 错误处理
            $('#techOptionsContainer').empty().html('加载失败');
            $.messager.alert('错误', '工艺数据加载失败，请重试！');
        }
    });
}

// 确认选择
function confirmTechSelection() {
    var selected = [];
    $('input[name="techOption"]:checked').each(function() {
        selected.push($(this).val());
    });

    $('#orderTechnology').textbox('setValue', selected.join(', '));
    $('#techModal').dialog('close');
}

/*========================================================================================================*/

function fee_grid() {
    $("#order_fee_grid").datagrid({
        url: 'orderFee/selectByMainId',
        striped: true,
        fit: true,
        // autoSave: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        height: 'auto',
        columns: [[
            {title: '编号', field: 'id', hidden: true, width: 50, align: 'center', halign: 'center'},
            {
                title: '日期',
                field: 'billDate',
                width: 100,
                align: 'center',
                halign: 'center',
                editor: {type: 'datebox', options: {required: false}}
            },
            {
                title: '费用名称',
                field: 'itemName',
                width: 150,
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {}}
            },
            {
                title: '金额',
                field: 'amount',
                width: 100,
                align: 'right',
                halign: 'center',
                formatter: formatter2,
                editor: {type: "numberbox", options: {readonly: true, precision: 2}}
            },
            {
                title: '备注',
                field: 'remark',
                width: 160,
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {}}
            },
        ]],
        onDblClickRow: function (index, row) {
            let orderFee = {id: row.id,billDate:row.billDate,itemName: row.itemName, amount: row.amount};
            $("#fee_form").form('load', orderFee);
        },
        onLoadSuccess: function (data) {
            compute_fee();
            $(this).datagrid('resize');
        },
        onResizeColumn: function (f, w) {
            if (w < 30) {
                if (f == 'clientId' || f == 'kilo' || f == 'billtypeId' || f == 'cutterId') {
                    $.messager.show({title: '提示', msg: '无法隐藏该列,因为该列为必输项'});
                    return;
                }
                $(this).datagrid('hideColumn', f);
                $.post("deploy/update.do", {menuId: 301, hidden: true, width: w, fieldname: f}, function (data) {
                    if (data.state == 200) {
                        sessionStorage.removeItem('bp_bpbill');
                    }
                }, "json");
            } else {
                $.post("deploy/update.do", {menuId: 301, hidden: false, width: w, fieldname: f}, function (data) {
                    if (data.state == 200) {
                        sessionStorage.removeItem('bp_bpbill');
                    }
                }, "json");
            }
        },
    });

    function compute_fee() {
        let data = $('#order_fee_grid').edatagrid('getRows');
        let qte = 0, amount = 0;
        for (let i = data.length - 1; i >= 0; i--) {
            amount += data[i].amount ? parseFloat(data[i].amount) : 0;
        }
        $('#order_fee_grid').edatagrid('reloadFooter', [{
            billDate: '合计',
            amount: amount.toFixed(2),
        }]);
    }
}

//计划费用模态窗 - 保存
function btn_saveData_fee() {
    let orderFee = $('#fee_form').serializeObject();
    if (!orderFee.itemName ) {
        $.messager.show({title: '提示', msg: '费用名称不允许为空！！'});
        return;
    }
    if (!orderFee.amount || orderFee.amount==0) {
        $.messager.show({title: '提示', msg: '费用金额不允许为空或0！！'});
        return;
    }
    orderFee.parentId = FEEPID;
    let url = orderFee.id ? 'orderFee/update' : 'orderFee/insert';
    $.ajax({
        url: url,
        contentType: 'application/json',
        data: JSON.stringify(orderFee),
        type: 'post',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            if (data.id) {
                btn_refresh_fee();
                btn_search();
                $.messager.show({title: '提示', msg: '成功'});
            } else {
                $.messager.show({title: '提示', msg: data.message});
            }
        }
    })
}

//刷新费用表格
function btn_refresh_fee() {
    $('#feeId').textbox('clear');
    $("#fee_form").form('load', {billDate:getCurrentDate()});
    $('#itemName').textbox('clear');
    $('#fee_amount').textbox('clear');
    $('#fee_remark').textbox('clear');
    $("#order_fee_grid").datagrid('load', {id: FEEPID});
}

//关闭费用模态窗
function btn_close_fee() {
    $('#fee_log').dialog('close');
    let orderFee = {billDate:'',client:'',orderNo:'',itemName:'',amount:'',remark:''}
    $("#fee_form").form('load', orderFee);
    FEEPID = null;
}

//删除费用
function btn_delete_fee() {
    let orderFee = $("#order_fee_grid").datagrid('getSelected');
    $.messager.confirm('确认', '确定删除选中行吗？不可恢复！', function (r) {
        if (r) {
            $.ajax({
                url: 'orderFee/deleteById/' + orderFee.id,
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                    if (data.data = '成功') {
                        btn_refresh_fee();
                        btn_search();
                        $.messager.show({title: '提示', msg: '成功'});
                    } else {
                        $.messager.show({title: '提示', msg: data.message});
                    }
                }
            })
        }
    })

}

function btn_cancel_add() {
    $('#order_log').dialog('open');
    setStatus(0)
    clear_log();
}

let FEEPID;

//序时表-制作订单费用
function btn_cancel_fee() {
    let index = getSelectedIndex();
    let orderFee;
    let kGrid;
    if (index == 0) kGrid = $("#v_sum_grid").data("kendoGrid");
    if (index == 1) kGrid = $("#v_grid").data("kendoGrid");
    // 获取当前选中行
    var selectedRow = kGrid.select();
    // 获取选中行的数据项
    var selectedData = kGrid.dataItem(selectedRow);
    if (!selectedData) {
        $.messager.show({title: '提示', msg: '请选中行后再试！！'});
        return;
    }
    FEEPID = selectedData.mainId;
    orderFee = {billDate: getCurrentDate(), client: selectedData.ctName, orderNo: selectedData.orderNo};
    $('#fee_log').dialog('open');
    $("#fee_form").form('load', orderFee);
    $("#order_fee_grid").datagrid('load', {id: selectedData.mainId});
}

/** 禁用Easyui form中的所有组件*/
function disableFormAllControl(ff) {
    $("input[textboxname]", ff).each(function (i, n) {
        $(n).textbox('disable');
    });
    $("input[switchbuttonname]", ff).each(function (i, n) {
        $(n).switchbutton('disable');
    });
    $(".easyui-linkbutton", ff).each(function (i, n) {
        $(n).linkbutton('disable');
    });
}

/** 启用Easyui form中的所有组件*/
function enableFormAllControl(ff) {
    $("input[textboxname]", ff).each(function (i, n) {
        $(n).textbox('enable');
    });
    $("input[switchbuttonname]", ff).each(function (i, n) {
        $(n).switchbutton('enable');
    });
    $(".easyui-linkbutton", ff).each(function (i, n) {
        $(n).linkbutton('enable');
    });
}

function btn_cancel_filter() {
    switch (getSelectedIndex()) {
        case 0:
            $('#v_sum_grid').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid').data('kendoGrid').dataSource.filter({});
            break;
        case 2:
            $('#v_fee_grid').data('kendoGrid').dataSource.filter({});
            break;
    }
}

function btn_search() {
    let index = getSelectedIndex();
    if (!stateFlag) stateFlag = 1;
    if (index == 0) $('#v_sum_grid').data('kendoGrid').dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue'),
        flag: stateFlag
    })
    if (index == 1) $('#v_grid').data('kendoGrid').dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue'),
        // flag: $('#flag').combobox('getValue')
        flag: stateFlag
    })
    if (index == 2) $('#v_fee_grid').data('kendoGrid').dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue')
    })
}

//获取当前选中标签页索引
function getSelectedIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

function getSelectedGrid() {
    let kendoGridID = '';
    switch (getSelectedIndex()) {
        case 0:
            kendoGridID = '#v_sum_grid';
            break;
        case 1:
            kendoGridID = '#v_grid';
            break;
        case 2:
            kendoGridID = '#v_fee_grid';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}


//列隐藏显示模态窗
function btn_open_column_list() {
    let kGrid = getSelectedGrid();
    let options = kGrid.getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="
                    resizable:true,iconCls:'icon-filter',width:200,height:400,modal:true,title:'列',
                    onClose:function(){$(this).dialog('destroy')}" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        kGrid.showColumn(opts.name);
                    } else {
                        kGrid.hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

// function btn_open_column_list() {
//     let kendoGridID = '#v_grid';
//     let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
//     if ($('#btn_open_column_list').length <= 0) {
//         let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'"
//                           class="easyui-dialog" id="btn_open_column_list">
//                    </div>`);
//         let form = $('<form style="width: 100%;height: 100%;"></form>')
//         for (let i of options) {
//             if (i.field) {
//                 let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
//                 <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
//                 labelWidth:120,value:true,name:'${i.field}'">
//                 </div>`);
//                 form.append(checkbox);
//             }
//         }
//         let container = $(`<div></div>`);
//         form.appendTo(div);
//         div.appendTo(container);
//         $('body').append(container);
//         $.parser.parse($('#btn_open_column_list').parent());
//         let formData = {};
//         options.map(item => {
//             formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
//         })
//         $('#btn_open_column_list form').eq(0).form('load', formData);
//         $('#btn_open_column_list form .easyui-checkbox').each(function () {
//             //  绑定事件
//             $(this).checkbox({
//                 onChange: function (checked) {
//                     let opts = $(this).checkbox('options');
//                     if (checked) {
//                         $(kendoGridID).data('kendoGrid').showColumn(opts.name);
//                     } else {
//                         $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
//                     }
//                 }
//             })
//         })
//     } else {
//         $('#btn_open_column_list').dialog('open');
//     }
// }

//  打印
function btn_print() {
    let start = $('#start').datebox('getValue');
    let end = $('#end').datebox('getValue');
    let storageId = $('#storageId').combobox('getValue');
    if (!start || !end || !storageId) {
        $.messager.alert('提示', '请选择日期和仓库', 'warning');
        return;
    }
    window.parent.FR.doURLPDFPrint({
        url: $(window.parent.document.body).data('report_url'),
        isPopUp: false,
        data: {
            reportlets: [{
                reportlet: '材料收发存汇总.cpt',
                start: start,
                end: end,
                storageId: storageId
            }]
        }
    });
}

function btn_export_excel() {
    switch (getSelectedIndex()) {
        case 0:
            $('#v_sum_grid').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid').data('kendoGrid').saveAsExcel();
            break;
        case 2:
            $('#v_fee_grid').data('kendoGrid').saveAsExcel();
            break;
    }
}

function btn_close() {
    window.parent.closeTab();
}

function createEditDialog(){
    // left:0,top:0
    let divElement = `
   <div id="editDialog" class="easyui-dialog" data-options="closed:true,">
    <form id="form_setBadQty" style="width: 100%;height: 100%;">
        <div class="easyui-layout" data-options="fit:true">
            <div id="west" data-options="region:'west',split:false" title="基础信息" style="width:300px;">
                <div class="input-group">
                    <input type="hidden"  id="iid" name="iid" >
                    <input type="hidden"  id="product_plan_dtl_id" name="product_plan_dtl_id">
                    <input type="hidden"  id="contact_company_id" name="contact_company_id">
                </div>

                <table id="table01" style="width: 100%">
                    <tr>
                    <td><input type="hidden"  id="material_order_bill_dtl_id" name="material_order_bill_dtl_id" /></td><!-- 材料明细主键 -->
                    <td><input type="hidden"  id="product_order_bill_dtl_id" name="product_order_bill_dtl_id" /></td>  <!-- 成品明细主键 -->
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="in_date" name="in_date" data-options="labelWidth:'100px',label:'生产入库日期：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="order_code" name="order_code" data-options="labelWidth:'100px',label:'订单号：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="ct_name" name="ct_name" data-options="labelWidth:'100px',label:'客户：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="product_coded" name="product_coded" data-options="labelWidth:'100px',label:'存货编码：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="pf_name" name="pf_name" data-options="labelWidth:'100px',label:'存货名称：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="plan_qty" name="plan_qty" data-options="labelWidth:'100px',
                            label:'生产计划数量：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_total" name="qty_total" data-options="labelWidth:'100px',onChange:function(){ updateGoodsQty() },
                            label:'过机数量：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_good" name="qty_good" data-options="labelWidth:'100px',label:'良品数：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_bad" name="qty_bad" data-options="labelWidth:'100px',label:'不良数：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="project_sid" name="project_sid" data-options="labelWidth:'100px',label:'工程：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                </table>
            </div>

<!--            <div data-options="region:'center',split:false" title="不良原因1">-->
<!--                <table id="table02" style="width: 100%">-->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad01" name="bad01" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'纸板不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad02" name="bad02" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'试机：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad03" name="bad03" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'投纸破损：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad04" name="bad04" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'进纸跑位：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad05" name="bad05" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'里纸过机：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                                            <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad06" name="bad06" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷露白：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad07" name="bad07" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷漏印、缺印：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad08" name="bad08" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷溢墨、重影、不匀：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad09" name="bad09" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'爆线：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad10" name="bad10" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'废纸压伤，破损：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad11" name="bad11" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'生产过程脏污、破损、折痕：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad12" name="bad12" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'糊箱不良（错位，内连，脱胶）：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--                </table>-->
<!--            </div>-->

            <div data-options="region:'center',split:false" title="不良原因" style="width:150px;">
                <table id="table03" style="width: 100%">
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad13" name="bad13" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'强度不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad14" name="bad14" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'模切不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad15" name="bad15" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'成形 使用不能：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad16" name="bad16" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'印刷不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad17" name="bad17" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'脏污.破损.折痕：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad18" name="bad18" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'粘合不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad19" name="bad19" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'其他：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    <tr>

                    <tr>
                        <td><input  class="easyui-numberbox" id="bad_money" name="bad_money" data-options="labelWidth:'160px',label:'不良损失金额：', labelAlign:'right',precision:2,readonly:true," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td align="right" style="padding-right: 110px">
                        <input id="bad_source_mill" name="bad_source_mill" class="easyui-checkbox" data-options="label:'不良原因-厂家：',labelWidth:100,labelPosition:'before',value:true,checked:false">
                        </td>
                    <tr>
                    </tr>
                        <td align="right" style="padding-right: 110px">
                        <input id="bad_source_project" name="bad_source_project" class="easyui-checkbox" data-options="label:'不良原因-工程内：',labelWidth:110,labelPosition:'before',value:true,checked:false">
                        </td>
                    </tr>
                    <tr>
                        <td><input type="hidden"  id="sales_price_withtax" name="sales_price_withtax" class="easyui-numberbox" data-options="precision:2"></td>
                    </tr>
                    <tr>
                        <td><input type="hidden"  id="sales_price_nottax" name="sales_price_nottax" class="easyui-numberbox" data-options="precision:2"></td>
                    </tr>
                    
                </table>
            </div>
        </div>
    </form>
</div>
`;

    // 2022年3月2日 21:58:28 将弹出模态窗中的该元素取消，在“不良损失金额”上面，“其他”下面
// </tr>
//     <td><input id="sales_price_withtax" name="sales_price_withtax" class="easyui-numberbox" data-options="label:'含税销售单价',precision:2" ></td>
//         </tr>
//         </tr>
//         <td><input id="sales_price_nottax" name="sales_price_nottax" class="easyui-numberbox" data-options="label:'不含税销售单价',precision:2"></td>
//         </tr>

    if ($('#editDialog').length <= 0) {
        $(divElement).appendTo($('body'));

        // 创建对话框后绑定事件
        //bindEvent_BadQtyCtl_batch();
    }

}

// 设置不良数量
function saveBadQty(){
    if( !check4Save() ) return;// 检查不合法则退出不保存
    const formData = serializeObject('form_setBadQty');
    console.log(formData);

    $.ajax({
        type : "POST",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(formData),
        url : URL_SAVE,
        success : function(res) {
            if(!res.success){
                msg(res.message);
                return
            }

            msg('保存成功');
            $(`#editDialog`).dialog({closed: true});
            refreshGrid();// 刷新表格
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
            // 旭纸业项目中通过 progress 锁定前端页面
            // $.messager.progress({title: '提示', text: '请稍候...', interval: 5000});
            // $.messager.progress('close');
        }
    })
}

// 初始化编辑用模态窗的数据 - 填充订单号、客户、存货编码等信息
function initEditDialog(){
    const selectedRows = getKendoGridSelectedRowData(KENDO_GRID_ID);
    if( !selectedRows || selectedRows.length <=0 ){
        $.messager.show({title: '提示', msg: '选中一行后再执行本操作！'});
        return false;
    }

    createEditDialog();// 先创建对话框

    const rowData = selectedRows[0];

    const formatedDate = new Date(rowData.in_date).format('yyyy-MM-dd');

    // 通过自定义方法给表单赋值
    // 该方法在打开对话框时会显示上一次的数据，关闭再次打开才会显示最新的数据
    // $(`#form_setBadQty`).setFormValue(rowData);
    // $(`#form_setBadQty`).setFormValue({
    //     in_date: formatedDate
    // });

    // 通过 load 方法给表单赋值
    rowData.in_date = formatedDate;
    $(`#form_setBadQty`).form('load',rowData);

    setTimeout(() => {
        updateBadQty();// 更新不良汇总数量
    },100);

    const sourceMill = rowData.bad_source_mill || false;
    const sourceProject = rowData.bad_source_project || false;
    $('#bad_source_mill').checkbox({checked:sourceMill});
    $('#bad_source_project').checkbox({checked:sourceProject});

    return true;
}

function serializeObject(formId) { /*将form表单内的元素序列化为对象，扩展Jquery的一个方法*/
    let o = {};
    let form = $(`#${formId}`);
    $.each(form.serializeArray(), function (index) {
        if (o[this['name']]) {
            o[this['name']] = o[this['name']] + "," + this['value'];
        } else {
            o[this['name']] = this['value'];
        }
    });
    return o;
}

// 2022年2月20日 08:29:40 chanchaw
// 保存前调用本方法检查当前数据是否合法，合法则返回 true，相反则返回 false，调用方不继续保存数据
// 检查内容如下：
// 1. 过机数 = 良品数 + 不良数
function check4Save(){
    const formData = serializeObject(EDIT_FORM_ID);
    if(!check4Save_qtyTotal(formData)) return false;

    return true;
}

// 检测：过机数 = 良品数量 + 不良数量
// 不等则返回 false
function check4Save_qtyTotal(formData){
    if( !formData ) return true;
    const qtyTotal = formData.qty_total || 0;
    const qtyGoods = formData.qty_good || 0;
    const qtyBad = formData.qty_bad || 0;

    const total = parseFloat(qtyTotal);
    const a = parseFloat(qtyGoods);
    const b = parseFloat(qtyBad);
    const total1 = a+b;

    if( total !== total1 ){
        msg('过机数 = 良品数 + 不良数。请检查数量设置是否正确！');
        return false;
    }

    return true;
}

// 不良原因控件 onChange 事件触发，传入参数是当前控件的最新值
function updateBadQty(currentVal){
    let sum1 = 0;
    for (let i = 0; i < BAD_CTL_ID.length; i++) {
        const val = $(`#${BAD_CTL_ID[i]}`).numberbox('getValue') || 0;
        sum1 += convert2Float(val);
    }
    $('#qty_bad').numberbox('setValue',sum1);

    // 不良数量有变动则同时更新良品数量
    updateGoodsQty();

    // 同时更新损失金额
    const priceWithTax = $('#sales_price_withtax').numberbox('getValue') || 0;
    const priceNoTax = $('#sales_price_nottax').numberbox('getValue') || 0;
    const moneyWithTax = priceWithTax * sum1;
    const moneyNoTax = priceNoTax * sum1;
    $('#bad_money').numberbox('setValue',moneyWithTax > 0 ? moneyWithTax : moneyNoTax || 0);
}

// 更新良品数量 = 过机数量 - 不良数量
function updateGoodsQty(){
    const qtyTotal = convert2Float($('#qty_total').numberbox('getValue') || 0);
    const qtyBad = convert2Float($('#qty_bad').numberbox('getValue') || 0);
    const qtyGoods = convert2Float(qtyTotal - qtyBad);
    $('#qty_good').numberbox('setValue',qtyGoods);
}


// 刷新表格
function refreshGrid(){
    $('#flag').checkbox('uncheck');
    $(`#${KENDO_GRID_ID}`).data("kendoGrid").dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue'),
        flag: 0
    });
}

// 2022年2月21日 16:32:31 chanchaw
// 批量绑定事件会导致中间栏 input 宽度最小
// 之后弃用该方法
function bindEvent_BadQtyCtl_batch(){
    for (let i = 0; i < BAD_CTL_ID.length; i++) {
        $(`#${BAD_CTL_ID[i]}`).numberbox({
            onChange: function(newVal,oldVal){
                //updateBadQty(newVal,oldVal);
            }
        });
    }

    // 过机数量修改后及时刷新良品数量
    $('#qtyTotal').numberbox({
        onChange: function(newVal,oldVal){
            updateGoodsQty();
        }
    });

    // 不良数量修改后及时刷新良品数量
    $('#qtyBad').numberbox({
        onChange: function(newVal,oldVal){
            updateGoodsQty();
        }
    });
}

// 行变色
function changeBackgroundColor(){
    let kGrid = $('#v_grid').data('kendoGrid');
    let gridRows = kGrid.tbody.find("tr");

    for(let i=0;i<gridRows.length;i++){
        const rowData = kGrid.dataItem(gridRows[i]);
        const mainState = rowData.mainState;

        if( mainState == 2){
            // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
            $(gridRows[i]).css("color", "blue"); // 修改颜色
        }
        // if( main_state == 0){
        //     // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
        //     $(gridRows[i]).css("color", "red"); // 修改颜色
        // }
    }
}

function changeBackgroundColor1(){
    let kGrid = $('#v_sum_grid').data('kendoGrid');
    let gridRows = kGrid.tbody.find("tr");

    for(let i=0;i<gridRows.length;i++){
        const rowData = kGrid.dataItem(gridRows[i]);
        const mainState = rowData.mainState;

        if( mainState == 2){
            // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
            $(gridRows[i]).css("color", "blue"); // 修改颜色
        }
        // if( main_state == 0){
        //     // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
        //     $(gridRows[i]).css("color", "red"); // 修改颜色
        // }
    }
}

function checkModifyPermission(){
    let ret = true;
    $.ajax({
        async: false,
        type : "GET",
        contentType: "application/json;charset=UTF-8",
        url : "quality/modify", // 验证是否有修改权限的后台API
        success : function(result) {
            if( !result.success ){
                messageAlertError('没有权限进行该操作！');
                ret = false;
            }
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
            // 旭纸业项目中通过 progress 锁定前端页面
            // $.messager.progress({title: '提示', text: '请稍候...', interval: 5000});
            // $.messager.progress('close');
        }
    })

    return ret;
}

// 初始化页面
function init(){
    const firstDay = curMonthFirstDay();
    const today = dateToStr('yyyy-MM-dd',new Date());
    const firstDayString = dateToStr('yyyy-MM-dd',firstDay);
    // $('#start').datebox('setValue',firstDayString);
    // $('#end').datebox('setValue',today);

    // 初始化右键菜单
    initContextMenu();
}

// 初始化右键菜单
function initContextMenu(){
    $(document).bind('contextmenu', function (e) {
        e.preventDefault();
        $('#mm').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
    });
}

// 拷贝当前行数据到粘贴板
function copyRowData(){
    let selectedRows = getSelectedRows();
    if (!selectedRows) {
        msg("选中行后再执行本操作！")
        return
    }

    let codedString = "";
    selectedRows.each(function (index, item) {
        let dataItem = $('#v_grid').data('kendoGrid').dataItem($(this));
        codedString = codedString + JSON.stringify(dataItem) + ",";
    })

    // 移除最后一个符号
    codedString = removeSuffix(codedString, ",");
    copyToClip(codedString);
    codedString.length > 0 ? $.messager.show({title: '提示', msg: '复制完毕！'}) : $.messager.show({
        title: '提示',
        msg: '复制了空白内容！'
    })
}

// 拷贝选中行的存货编码到剪贴板 - 可选中多行
function copyCoded() {
    let selectedRows = getSelectedRows();
    if (!selectedRows) {
        msg("选中行后再执行本操作！")
        return
    }
    let codedString = "";
    selectedRows.each(function (index, item) {
        let dataItem = $('#v_grid').data('kendoGrid').dataItem($(this));
        codedString = codedString + dataItem.product_coded + ","
    })

    // 移除最后一个符号
    codedString = removeSuffix(codedString, ",");
    copyToClip(codedString);
    codedString.length > 0 ? msg("拷贝完毕！") : msg("拷贝了空白内容！")
}

// 获取表格选中的多行
function getSelectedRows() {
    return $('#v_grid').data('kendoGrid').select();
}

/**
 * 复制内容到粘贴板
 * content : 需要复制的内容
 * message : 复制完后的提示，不传则默认提示"复制成功"
 */
function copyToClip(content, message) {
    var aux = document.createElement("input");
    aux.setAttribute("value", content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
    if (message == null) {
        // alert("复制成功");
    } else {
        alert(message);
    }
}

/**
 * 2021年7月4日 23:05:58
 * chanchaw
 * raw：传入原始字符串
 * suffix：字符串最后一个字符符合则删除后返回
 */
function removeSuffix(raw, suffix) {
    let str = raw.toString();
    let last = str.substr(str.length - 1, 1);
    if (last == suffix)
        str = str.substr(0, str.length - 1)
    return str;
}